<?php

/***  DOCUMENTATION LAYER

	Array to Cols Function (Array Library)

	Last Update: Mar 2007
	Author: Tom at klenwell@gmail.com

	FUNCTIONS
	
		array_lottery($CANDIDATES, $num_picks=1)


  NOTES
		CANDIDATES should be an associative array where the key is an id and the value
		is the (raw) number of chances that element has of being picked.
		
		Not at all optimized, but suitable in many practical situations

______________________________________________________________________________*/


// array_lottery
/*____________________________________________________________________________*/
function array_lottery($CANDIDATES, $num_picks=1) 
{
// *** DATA

	// internal
	$num_candidates = count($CANDIDATES);
	$BALL = array();
	 
	// Return
	$PICKS = array();
	

// *** MANIPULATE
	
	// assign lottery balls
	for ( $c=0;$c<$num_candidates;$c++ )
	{
		$lots = $CANDIDATES[$c];
		for ( $i=0;$i<$lots;$i++ ) $BALL[] = $c;
	}
	
	// pick winners
	while ( $num_picks > 0 )
	{
		$ball_count = count($BALL);
		$this_pick = $BALL[array_rand($BALL)];

		for ( $i=0; $i<$ball_count; $i++ )
		{
			if ( $BALL[$i] == $this_pick ) unset($BALL[$i]);
		}
		
		$PICKS[] = $this_pick;
		$num_picks--;
		sort($BALL);
	}

// *** RETURN

	return $PICKS;
} 
/*____________________________________________________________________________*/


// Testbed
/*____________________________________________________________________________*/


/*____________________________________________________________________________*/

?>
